//	                           __    __
//	| |    | |  | || || | |    \ \  / /  | |
//	| |____| |  | |      | |    \ \/ /   | |
//	| |____| |  | |      | |     \  /    | |
//	| |    | |  | |      | |     /  \    | |
//  | |    | |  | |      | |    / /\ \   | |
//  | |    | |  | || || | |    /_/  \_\  | |
//
//  AppDelegate.m
//  PublicProject
//
//  Created by TianHe_Wsk on 15/10/14.
//  Copyright (c) 2015年 H.D.X. All rights reserved.
//

#import "AppDelegate.h"
#import "UserCenterVC.h"
#import "CunjianDetailVC.h"
#import "CunquHomeVC.h"

#import "UIViewController+Swizzled.h"

//极光推送
static NSString *appKey = @"580bb526977ee426b548c4e5";
//static NSString *channel = @"Publish channel";
//
//static BOOL isProduction = FALSE;


#ifdef DEBUG
#define IS_PRODUCTION NO // 0 (默认值)表示采用的是开发证书，即测试环境
#define CHANNEL @"debug"
#else
#define IS_PRODUCTION YES // 1 表示采用生产证书,即生产环境
#define CHANNEL @"app store"
#endif

#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h> // 这里是iOS10需要用到的框架
#endif
//腾讯bugly
#import <Bugly/Bugly.h>
#define BUGLY_APP_ID @"684c6e2af9"
//登录界面
#import "LoginVC.h"
#import "CSMyOrderConfirmingTVC.h"
#import "OrderDetailsVC.h"
@interface AppDelegate ()<JPUSHRegisterDelegate>{
    UILabel *_infoLabel;
    UILabel *_tokenLabel;
    UILabel *_udidLabel;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (!IS_PRODUCTION) {
        // 程序页面跟踪工具, 在测试时使用
        SWIZZ_IT
    }
    
    //网络初始化
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    // 动态刷新服务器地址
    [self downloadHostFileAndChageHost];
   
    // 初始化bugly
    [self initBugly];
    
    // 初始化数据库
     [self initFDB];
    
    // 初始化推送(JPush)
    [self initJpush:application didFinishLaunchingWithOptions:launchOptions];
    
    // 初始化UI
    [self initUI];
    
    // 初始化默认语言
    [self initLanguage];
    
    return YES;
}


//推到后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
//    [application setApplicationIconBadgeNumber:0];
    NSLog(@"程序进入后台");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    //取消所有通知
//    [application setApplicationIconBadgeNumber:0];
//    [application cancelAllLocalNotifications];
}

//进到前台
- (void)applicationDidBecomeActive:(UIApplication *)application {

    //判断是否需要刷新头像图片
    [THMangerTool setUpHeadDateTime:NO];
}

- (void)applicationWillTerminate:(UIApplication *)application {

}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSLog(@"收到本地通知回到");
    
}

#pragma mark - 初始化 UI
- (void)initUI {
    
    //导航栏 状态栏
    {
        /*
         ================
         启动隐藏状态栏 运行隐藏状态栏 首先要在plist 中设置key Status bar is initially hidden 设置YES
         ================
         */
        //   [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
        //启动是是否隐藏状态栏
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        
        /*
         ================
         统一导航颜色
         ================
         */
        //X色导航 NavigationControllerImageByColor
        [[UINavigationBar appearance] setBackgroundImage:[UtilCheck NavigationControllerImageByColor: SYSTEM_COLOR] forBarMetrics:UIBarMetricsDefault];
        
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
   
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:[UtilCheck hexStringToColor:myBackColor alpha:1]];
    // 设置首页
    [self setUpMainViewControllerOrLoginViewController:NO];
}

#pragma mark- 初始化数据库
-(void)initFDB{
    [FMDatabase initTable];
}

#pragma  mark- 初始化默认语言
- (void)initLanguage {
    // 如果是默认语言根据系统语言设置语言
    if ([THMangerTool getLanageType] == NSLanguageDefault) {
        [UtilCheck setLanguage:[THMangerTool getPreferredLanguage]];
    }
    else {
        [UtilCheck setLanguage:[THMangerTool getLanageType]];
    }
    
}

#pragma mark - 如果使用SSO（可以简单理解成客户端授权），以下方法是必要的
- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url {
    
    if ([url.host isEqualToString:@"BoDenTech.BJ"]) {
        return [[UIApplication sharedApplication] openURL:url];
    }
    return YES;
    
}


//iOS 4.2+
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([url.host isEqualToString:@"BoDenTech.BJ"])
    {
        
        return [[UIApplication sharedApplication] openURL:url];
    }
    
        return YES;
}


// ios9.0 之后用这个方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    
    if ([url.host isEqualToString:@"BoDenTech.BJ"])
    {
        
        return  [[UIApplication sharedApplication] openURL:url];
    }

    return YES;
    
}



#pragma mark- bugly 统计
#pragma mark-

#pragma mark 初始化bugly
-(void)initBugly{
    
    
    // Get the default config
    BuglyConfig * config = [[BuglyConfig alloc] init];
    
    // Open the debug mode to print the sdk log message.
    // Default value is NO, please DISABLE it in your RELEASE version.
#if DEBUG
    config.debugMode = YES;
#endif
    
    // Open the customized log record and report, BuglyLogLevelWarn will report Warn, Error log message.
    // Default value is BuglyLogLevelSilent that means DISABLE it.
    // You could change the value according to you need.
    config.reportLogLevel = BuglyLogLevelWarn;
    
    // Open the STUCK scene data in MAIN thread record and report.
    // Default value is NO
    config.blockMonitorEnable = YES;
    
    // Set the STUCK THRESHOLD time, when STUCK time > THRESHOLD it will record an event and report data when the app launched next time.
    // Default value is 3.5 second.
    config.blockMonitorTimeout = 1.5;
    
    // Set the app channel to deployment
    config.channel = @"APPStore";
    
    // NOTE:Required
    // Start the Bugly sdk with APP_ID and your config
    [Bugly startWithAppId:BUGLY_APP_ID config:config];
    
    // Set the customizd tag thats config in your APP registerd on the  bugly.qq.com
    [Bugly setTag:1998];
 
    if([THMangerTool isLogin]){
        
        //用户信息
        [Bugly setUserIdentifier:[NSString stringWithFormat:@"UID:%@ UNM:%@",[THMangerTool getAccountInfo].accout,[THMangerTool getAccountInfo].realName]];//[NSProcessInfo processInfo].hostName
        
        [Bugly setUserValue:[NSString stringWithFormat:@"UID:%@ UNM:%@",[THMangerTool getAccountInfo].accout,[THMangerTool getAccountInfo].realName] forKey:@"匿名"];//[NSProcessInfo processInfo].processName
    }
    else{
    
    //用户信息
    [Bugly setUserIdentifier:[NSString stringWithFormat:@"UNM:%@",@"IphoneUser"]];//[NSProcessInfo processInfo].hostName
    
    [Bugly setUserValue:[NSString stringWithFormat:@"UNM:%@",@"IphoneUser"] forKey:@"匿名"];//[NSProcessInfo processInfo].processName
    }
    
    
    // NOTE: This is only TEST code for BuglyLog , please UNCOMMENT it in your code.
//    [self performSelectorInBackground:@selector(testLogOnBackground) withObject:nil];
}

/**
 *    @brief TEST method for BuglyLog
 */
- (void)testLogOnBackground {
    int cnt = 0;
    while (1) {
        cnt++;
        
        switch (cnt % 5) {
            case 0:
                BLYLogError(@"Test Log Print %d", cnt);
                break;
            case 4:
                BLYLogWarn(@"Test Log Print %d", cnt);
                break;
            case 3:
                BLYLogInfo(@"Test Log Print %d", cnt);
                BLYLogv(BuglyLogLevelWarn, @"BLLogv: Test", NULL);
                break;
            case 2:
                BLYLogDebug(@"Test Log Print %d", cnt);
                BLYLog(BuglyLogLevelError, @"BLLog : %@", @"Test BLLog");
                break;
            case 1:
            default:
                BLYLogVerbose(@"Test Log Print %d", cnt);
                break;
        }
        
        // print log interval 1 sec.
        sleep(1);
    }
}

#pragma mark- JPush 推送
#pragma mark-

#pragma mark 推送初始化
-(void)initJpush:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    //收到通知，就进入某个页面
    if (launchOptions != nil) {
        NSLog(@"收到推送");
        /** app进程被杀死后，启动app获取推送消息 */
        NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        NSLog(@"%@",userInfo);
        
    }
    // 注册apns通知
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) // iOS10
    {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) // iOS8, iOS9
    {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    else // iOS7
    {
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert) categories:nil];
    }
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:CHANNEL
                 apsForProduction:IS_PRODUCTION
            advertisingIdentifier:nil];
    
    NSLog(@"%@,%d",CHANNEL,IS_PRODUCTION);
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
}


#pragma mark 收到推送消息调用

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

//------iOS10是通过JPUSHRegisterDelegate实现的回调----
// iOS10 support 应用在前台时通知回调
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
        [self showNotification:userInfo];
    }
    
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}


// iOS 10 support 程序进入后台, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];

        [self showNotification:userInfo];
    }
    completionHandler();    // 系统要求执行这个方法
}
#endif


/**
 *  iOS 7..<iOS 10 后台收到通知后,点击通知后调用 或 前台收到通知时调用
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    // 更新显示的徽章个数
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge--;
    badge = badge >= 0 ? badge : 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
    [self showNotification:userInfo];
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


// iOS 6 support -- 本地通知回调函数，当应用程序在前台时调用,当应用在后台是点击通知回调
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


#pragma mark 系统方法 与 JPush相关

/**
 程序进入前台设置bage 更改图标上显示的数字

 @param application
 */
- (void)applicationWillResignActive:(UIApplication *)application {
    [JPUSHService setBadge:0];//重置JPush服务器上面的badge值。如果下次服务端推送badge传"+1",则会在你当时JPush服务器上该设备的badge值的基础上＋1；
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//apple自己的接口，变更应用本地（icon）的badge值；
}


// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    [JPUSHService registerDeviceToken:deviceToken];
    [self registerDeviceToken];
    
}

// 注册deviceToken失败，此处失败， 一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"未授权推送");
}

#pragma mark   通知监听

- (void)networkDidSetup:(NSNotification *)notification {
    
    NSLog(@"已连接");
    
}

- (void)networkDidClose:(NSNotification *)notification {
    
    NSLog(@"未连接");
    
}

- (void)networkDidRegister:(NSNotification *)notification {
    
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
}

- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
}


#pragma mark 这部分是官方demo里面给的, 也没实现什么功能, 放着以备不时之需

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler
{
    
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
    
}
#endif



#pragma mark 推送处理 -- 展示信息
- (void)showNotification:(NSDictionary *)userInfo{
   
    NSString *title=@"";
  __block   NSString *text = @"";
    
    NSLog(@"userinfo 是%@",userInfo);
    
    NSInteger type=0;
    if([[[userInfo  valueForKey:@"aps"] objectForKey:@"alert"] isKindOfClass :[NSDictionary class]]){
        title=[[[userInfo  valueForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"title"];
        text = [[[userInfo  valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"body"];
    }else{
        return;
    }
    if([[userInfo allKeys]containsObject:@"type"]){
        type=[[userInfo  objectForKey:@"type"] integerValue];
    }
    
    NSInteger isAlarm = 0;
    isAlarm = [[userInfo  objectForKey:@"isAlarm"] integerValue];
    //这里处理头图标
    UIImage *img=nil;
    NSMutableArray *btns = [[NSMutableArray alloc]init];
    
    if (isAlarm == 0) {
        [btns addObject:[THMangerTool language:@"show.gotIt"]];
        [btns addObject:[THMangerTool language:@"show.viewDetail"]];
        
    }
    else {//只有我知道了
        [btns addObject:[THMangerTool language:@"show.gotIt"]];
    }
    
    
    switch (type) {
            
        case 0://通知取故障件接口
        {
            img=BDFILEIMAGENAEM(@"Home/img_pack");
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"orderCode"]= [userInfo objectForKey:@"orderCode"];
            params[@"sendUserId"]= [userInfo objectForKey:@"sendUserId"];

            [AFHttpTool postJsonDatawithUrl:@"getPushMessageDetail" parameters:params success:^(id responseObject) {
                [[BDHUD sharedManager] dismissHUD];
                
                NSDictionary *headDic = responseObject[@"head"];
                
                if ([headDic[@"status"] intValue] == 1) {
                    text = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"] objectForKey:@"message"]];
                    
                    
                    
                    [[BDHUD sharedManager] showViewToView:nil ContentType:type headImage:img headTitle:title headColor:nil text:text bottons:btns click:^(NSInteger index, id responseObject) {
                        
                        if (index == 1 ) {
                            
                            if (type <= 2) {
                                CSMyOrderConfirmingTVC *vc = [[CSMyOrderConfirmingTVC alloc]init];
                                vc.orderCode = [userInfo objectForKey:@"orderCode"];
                                [vc getOrderDetails];
                                [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
                            } else {
                                OrderDetailsVC *vc = [[OrderDetailsVC alloc]init];
                                vc.orderCode = [userInfo objectForKey:@"orderCode"];
                                [vc getOrderDetails];
                                [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
                            }
                        }
                    }];

                }
                
                
                
            } fail:^(id responseObject, NSError *error) {
                [[BDHUD sharedManager] dismissHUD];
                
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.take.failure"]];
            }];


        }
            break;
            
        case 1:
        {
            //客户 发货提醒
            img=BDFILEIMAGENAEM(@"Home/img_deliver");
        }
            break;
        case 2:
        {
            //客户 发货提醒
            img=BDFILEIMAGENAEM(@"Home/img_order");
        }
            break;
        case 3:
        {
            //客户 发货提醒
            img=BDFILEIMAGENAEM(@"Home/img_pack");
        }
            break;
        case 4:
        {
            //仓库 发货提醒
            title=[THMangerTool language:@"show.deliverRemind"];
            img=BDFILEIMAGENAEM(@"Home/img_pack");
        }
            break;
        case 5:
        {
            //客服 待确认提醒
            //            title=[THMangerTool language:@"show.deliverRemind"];
            img=BDFILEIMAGENAEM(@"Home/img_pack");
            
        }
            break;
        case 6:
        {
            // 客服 订单发货提醒
            // title = [THMangerTool language:@"show.deliverRemind"];
            img=BDFILEIMAGENAEM(@"Home/img_pack");
        }
            break;
        case 7:
        {
            // 客服 订单收货提醒
            // title=[THMangerTool language:@"show.deliverRemind"];
            img=BDFILEIMAGENAEM(@"Home/img_pack");
        }
            break;
        case 8:
        {
            // 客服 客户延时送达提醒
            // title=[THMangerTool language:@"show.deliverRemind"];
            img=BDFILEIMAGENAEM(@"Home/img_pack");
        }
            break;
            
            
        default:{
            img=BDFILEIMAGENAEM(@"Home/img_pack");
        }
            break;
    }
    
    if (type != 0) {
        [[BDHUD sharedManager] showViewToView:nil ContentType:type headImage:img headTitle:title headColor:nil text:text bottons:btns click:^(NSInteger index, id responseObject) {
            
            if (index == 1 ) {
                
                if (type <= 2) {
                    CSMyOrderConfirmingTVC *vc = [[CSMyOrderConfirmingTVC alloc]init];
                    vc.orderCode = [userInfo objectForKey:@"orderCode"];
                    [vc getOrderDetails];
                    [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
                }else if (type ==3 && isAlarm ==3){
                    CunjianDetailVC *vc = [[CunjianDetailVC alloc]init];
                    vc.titlename = [[userInfo  objectForKey:@"type_operation"] isEqualToString:@"2"] ? [UtilCheck language:@"order.qudetail"]:[UtilCheck language:@"order.cundetail"];
                    vc.orderCode = [userInfo  objectForKey:@"code_operation"];
                    vc.isQujian = [[userInfo  objectForKey:@"type_operation"] isEqualToString:@"1"] ? @"0" : @"1";
                    [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
                }
                else {
                    OrderDetailsVC *vc = [[OrderDetailsVC alloc]init];
                    vc.orderCode = [userInfo objectForKey:@"orderCode"];
                    [vc getOrderDetails];
                    [[self getCurrentVC].navigationController pushViewController:vc animated:YES];
                }
            }
        }];
  
    }

}

#pragma mark- 初始化首页
//重新登录
-(void)Relogin{
    
    LoginVC *loginVC = [[LoginVC alloc] init];
    loginVC.isdismiss=YES;
    CustomNavigationController *vc = [[CustomNavigationController alloc ]initWithRootViewController:loginVC];
    
    [self.window.rootViewController presentViewController:vc animated:YES completion:^{
        
    }];
}

/**
 *  初始化首页
 */
-(void)setUpMainViewControllerOrLoginViewController:(BOOL)isLogn{
    
    //显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    //修改颜色
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
#pragma mark 进入主页
    if([THMangerTool isLogin]){
        THUserInfoModel *model = [THMangerTool getAccountInfo];
        if ([model.isVendor isEqualToString:@"1"]) {
             CunquHomeVC  *mainViewController = [[CunquHomeVC alloc] init];
            CustomNavigationController *vc = [[CustomNavigationController alloc ]initWithRootViewController:mainViewController];
            self.window.rootViewController = vc;
        }
        else{
        MainVC *mainViewController = [[MainVC alloc] init];
        CustomNavigationController *vc = [[CustomNavigationController alloc ]initWithRootViewController:mainViewController];
        self.window.rootViewController = vc;
        }
        
        //注册通知
        [self registerDeviceToken];
        
        [self.window makeKeyAndVisible];
    }
    else{
#pragma mark 进入登录界面
        LoginVC *loginVC = [[LoginVC alloc] init];
        CustomNavigationController *vc = [[CustomNavigationController alloc ]initWithRootViewController:loginVC];
        self.window.rootViewController = vc;
        [self.window makeKeyAndVisible];
    }
}


#pragma mark- 从特定服务器上读取TXT文本内的服务器地址
//     [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isDefaultHost"];

// 即:在APP启动过程中,从一个固定的地址下载一个存放服务器地址(eg:htttp://13.13.13.200:9090/SepWeb/)的TXT格式文件,从文件中读取服务器地址,把当前默认APP中数据请求的地址更换为更换为该地址.

- (void)downloadHostFileAndChageHost {
    
    // http://118.249.86.65:57701/SpmWeb/server.txt
    // http://ogrozh56n.bkt.clouddn.com/sever.txt
// 放在阿里云服务器
    NSURLSessionTask *getURLTask = [AFHttpTool getStringFromTxtFileURLString:@"http://tigershark.vip/serverSPM.txt" completion:^(NSString *resultString, NSError *error) {
      if (error) {
          NSLog(@"服务器地址请求失败.");
      }
        
        NSLog(@"问问%@",resultString);
        resultString = [NSString stringWithFormat:@"%@/",resultString];
        [THMangerTool setRecommendHost:resultString];
  }];
    
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [getURLTask cancel];
    });
}

#pragma mark - 在"个人中心"更改语言后调用
-(void)setLanagne{
    
    MainVC *mainViewController = [[MainVC alloc] init];
    CustomNavigationController *vc = [[CustomNavigationController alloc ]initWithRootViewController:mainViewController];
    self.window.rootViewController = vc;
    
    //注册通知
    [self registerDeviceToken];
    [self.window makeKeyAndVisible];
    self.window.alpha=0.95;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionTransitionNone animations:^{
        self.window.alpha=1;
    } completion:^(BOOL finished) {
        
        UserCenterVC *v=[[UserCenterVC alloc] init];
        [mainViewController.navigationController pushViewController:v animated:YES];
    }];
}

#pragma mark- 注册通知,将deviceToken传给服务器
/**
 *  注册通知
 */
-(void)registerDeviceToken{
    if([THMangerTool isLogin]&&[self isAllowedNotification]){
        NSString * registrationID= [JPUSHService registrationID];
        if([UtilCheck DataIsNuLL:registrationID]){
            return;
        }
        
        [AFHttpTool postJsonDatawithUrl:@"bindPush" parameters:[NSDictionary dictionaryWithObjectsAndKeys:registrationID,@"token", nil] success:^(id responseObject) {
            NSLog(@"----registrationID:%@",registrationID);
        } fail:^(id responseObject, NSError *error) {
            
        }];
    }
}

#pragma mark 获取系统通知权限
-(BOOL)isAllowedNotification {
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    if (UIUserNotificationTypeNone != setting.types) {
        return YES;
    }
    
    return NO;
}


#pragma mark- 跳转到该APP的设置中心
/**
 *  修改推送开光
 *
 *  @param status YES  打开 NO关闭
 *
 */
-(BOOL)setJpushStatus:(BOOL)status{
    
    //前往设置中心
    NSURL *url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
    return NO;
}

#pragma mark- 获取APP当前展示的 Controller
- (UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];   //  这方法下面有详解
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        CustomNavigationController * nav = (CustomNavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        // UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[CustomNavigationController class]]) {
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.shouldChangeOrientation == YES) {
        return UIInterfaceOrientationMaskLandscape;
    }
    else
    {
        return UIInterfaceOrientationMaskPortrait;
    }
}


@end

